package com.qst.crop.controller;

import com.qst.crop.common.Result;
import com.qst.crop.common.StatusCode;
import com.qst.crop.entity.Reserve;
import com.qst.crop.service.ReserveService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author QST
 * @Description 预约模块
 * @Date 2021-08-24
 */
@RestController
@RequestMapping("/reserve")
@Tag(name = "预约模块接口")
@CrossOrigin
public class ReserveController {
    @Autowired
    private ReserveService reserveService;

    //添加预约
    @Operation(summary = "添加预约")
    @PostMapping("/add")
    public Result<Reserve> addReserve(@RequestBody Reserve reserve) {
        // 获取当前登录用户信息并设置预约者
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        String currentUsername = principal.getUsername();
        reserve.setQuestioner(currentUsername);
        
        Reserve saved = reserveService.insert(reserve);
        return new Result<Reserve>(true, StatusCode.OK, "添加成功", saved);
    }

    /**
     * 查询个人预约
     *
     * @param questioner 咨询者
     * @return 查询结果
     */
    @Operation(summary = "查询个人预约")
    @GetMapping("/selectByKind/{questioner}")
    public Result<List<Reserve>> selectByQuestioner(@PathVariable("questioner") String questioner) {
        System.out.println("=== ReserveController.selectByQuestioner 被调用 ===");
        System.out.println("传入的questioner参数: " + questioner);
        
        // 获取当前登录用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        String currentUsername = principal.getUsername();
        
        System.out.println("当前登录用户: " + currentUsername);
        
        // 直接使用当前登录用户查询，忽略前端传递的参数
        System.out.println("开始查询用户预约记录...");
        List<Reserve> reserves = reserveService.selectByQuestioner(currentUsername);
        System.out.println("查询到的预约记录数量: " + (reserves != null ? reserves.size() : "null"));
        System.out.println("预约记录详情: " + reserves);
        
        return new Result<List<Reserve>>(true, StatusCode.OK, "查询成功", reserves);
    }

    /**
     * 根据ID修改预约
     *
     * @param reserve 预约实体
     * @return 修改结果
     */
    @Operation(summary = "根据ID修改预约")
    @PutMapping("/updateById")
    public Result<Reserve> updateById(@RequestBody Reserve reserve) {
        Reserve updated = reserveService.updateById(reserve);
        return new Result<Reserve>(true, StatusCode.OK, "修改成功", updated);
    }

    /**
     * 根据ID删除预约
     *
     * @param id 预约ID
     * @return 删除结果
     */
    @Operation(summary = "根据ID删除预约")
    @DeleteMapping("/deleteReserveById/{id}")
    public Result<Boolean> deleteReserveById(@PathVariable("id") Integer id) {
        boolean result = reserveService.deleteById(id);
        return new Result<Boolean>(true, StatusCode.OK, "删除成功", result);
    }

    /**
     * 查询所有预约
     *
     * @return 查询结果
     */
    @Operation(summary = "查询所有预约")
    @GetMapping("/selectAll")
    public Result<List<Reserve>> selectAll() {
        List<Reserve> reserves = reserveService.selectAll();
        return new Result<List<Reserve>>(true, StatusCode.OK, "查询成功", reserves);
    }

    /**
     * 根据ID查询预约
     *
     * @param id 预约ID
     * @return 查询结果
     */
    @Operation(summary = "根据ID查询预约")
    @GetMapping("/selectld/{id}")
    public Result<Reserve> selectById(@PathVariable("id") Integer id) {
        Reserve reserve = reserveService.queryById(id);
        return new Result<Reserve>(true, StatusCode.OK, "查询成功", reserve);
    }

    // 测试接口：直接查询用户预约记录（用于调试）
    @Operation(summary = "测试接口：直接查询用户预约记录")
    @GetMapping("/test/selectByQuestioner/{questioner}")
    public Result<List<Reserve>> testSelectByQuestioner(@PathVariable("questioner") String questioner) {
        System.out.println("=== 预约测试接口被调用 ===");
        System.out.println("查询用户: " + questioner);
        
        try {
            List<Reserve> reserves = reserveService.selectByQuestioner(questioner);
            System.out.println("查询结果: " + reserves);
            return new Result<List<Reserve>>(true, StatusCode.OK, "测试查询成功", reserves);
        } catch (Exception e) {
            System.out.println("查询异常: " + e.getMessage());
            e.printStackTrace();
            return new Result<List<Reserve>>(false, StatusCode.ERROR, "查询失败: " + e.getMessage(), null);
        }
    }

}